﻿using System;
using System.Linq;
using System.Text.RegularExpressions;
using Gp.Scripts.Core;
using QFramework;
using UnityEngine.InputSystem;

namespace Gp.Input
{
    /// <summary>
    ///  按键输入映射表。
    /// </summary>
    public enum InputMapCode
    {
        Interact = 1,
        Tab = 2,
        Exit = 3,
        Pause = 4,
        PickUp = 5,
        Quest = 6,
        DisablePuzzle = 7,
    }


    public enum InputTriggerType
    {
        /// 按键输入开始
        Started = 1,

        /// 按键长按
        Performed = 2,

        /// 按键输入结束
        Canceled = 3,
    }

    public static class InputMapCodeExtend
    {
        public static string KeyPath(this InputMapCode code)
        {
            var binding = code.KeyAction().bindings;
            if (binding.Count == 0) return "";
            var str = binding[0].path;

            str = new Regex("^<.*>/").Replace(str, "");
            return str.ToUpper();
        }


        public static InputAction KeyAction(this InputMapCode code)
        {
            var input = Global.Get<InputManager>().InputAction.City;
            return code switch
            {
                InputMapCode.Interact => input.Interact,
                InputMapCode.Tab => input.Tab,
                InputMapCode.Exit => input.Exit,
                InputMapCode.PickUp => input.PickUp,
                InputMapCode.Quest => input.Quest,
                InputMapCode.DisablePuzzle => input.DisablePuzzle,
                InputMapCode.Pause => input.Pause,
                _ => throw new ArgumentOutOfRangeException(nameof(code), code, null)
            };
        }



        public static bool Triggered(this InputMapCode code)
        {
            return code.KeyAction().triggered;
        }


        /// <summary>
        ///  按输入层级决定按键触发
        /// </summary>
        /// <param name="code"></param>
        /// <param name="logicLayer"></param>
        /// <returns></returns>
        public static bool LayerTriggered(this InputMapCode code, params InputLayer[] logicLayer)
        {
            int layer = logicLayer.Aggregate(0, (current, v) => current | (int) v);
            return Global.Get<InputLayerSystem>().IsLayer(layer) && code.Triggered();
        }

        /// <summary>
        ///  按输入层级决定按键触发
        /// </summary>
        /// <param name="code"></param>
        /// <param name="logicLayer"></param>
        /// <returns></returns>
        public static bool LayerTriggered(this InputMapCode code, int logicLayer)
        {
            return Global.Get<InputLayerSystem>().IsLayer(logicLayer) && code.Triggered();
        }
    }
}